package com.fouram.web.utils;

import cn.hutool.core.io.FileUtil;
import io.itit.itf.okhttp.FastHttpClient;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;

/**
 * 文件上传/下载工具类
 * @author liup
 */
@Slf4j
public class FileUpDownLoadUtils {

	public static String getYmdBasePath(){
		LocalDateTime now = LocalDateTime.now();
		int year = now.getYear();
		int month = now.getMonthValue();
		int day = now.getDayOfMonth();
		return "/" + year + "/" + month + "/" + day + "/";
	}

	/**
	 * 文件上传保存到本地文件
	 * @param multipartFile
	 * @param fileFolder
	 * @param fileName
	 * @return
	 */
	public static String upload(MultipartFile multipartFile, String fileFolder, String fileName) {
		if(multipartFile == null){
			return null;
		}
		String ymdBasePath = getYmdBasePath();
		copyFile(multipartFile, fileFolder + ymdBasePath, fileName);
		return ymdBasePath + fileName;
	}

	@SneakyThrows
	private static void copyFile(MultipartFile multipartFile, String dir, String fileName) {
		InputStream in = multipartFile.getInputStream();
		File file = new File(dir, fileName);
		if (!file.exists()) {
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			file.createNewFile();
		}
		FileUtils.copyInputStreamToFile(in, file);
		// 另一种方式
		// multipartFile.transferTo(file);
	}

	/**
	 * 以文件流返回
	 * @param response
	 * @param fullFilePath
	 * @param fileName
	 * @throws IOException
	 */
	public static void writeStream(HttpServletResponse response, String fullFilePath, String fileName) throws IOException {
		byte[] data = FileUtil.readBytes(fullFilePath);
		response.reset();
		response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
		response.setHeader("Content-Length", String.valueOf(data.length));
		response.setContentType("application/octet-stream;charset=UTF-8");
		OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
		outputStream.write(data);
		outputStream.flush();
		outputStream.close();
		response.flushBuffer();
	}

	/**
	 * 根据文件url下载文件
	 * @param savePath
	 * @param fileUrl
	 * @throws Exception
	 */
	public static void downloadFileByUrl(String savePath, String fileUrl) throws Exception {
		File file = new File(savePath);
		if (!file.exists()) {
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			file.createNewFile();
		}
		InputStream is = FastHttpClient.get().url(fileUrl).build().execute().byteStream();
		io.itit.itf.okhttp.util.FileUtil.saveContent(is, file);
	}
}
